<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="常量池占据了 class 文件很大一部分数据，里面存放着各式各样的常量信息，包括数字和字符串常量、类和接口名、字段和方法名等。本节将详细介绍常量池和各种常量。  常量池在 class 文件中格式123456ClassFile &amp;#123;  ...  u2 constant_pool_count;	//常量池大小  cp_info constant_pool[constant_pool_coun">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(5)-分析class文件-常量池">
<meta property="og:url" content="https://zachaxy.github.io/2017/05/09/手写JVM系列-5-分析class文件-常量池/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="常量池占据了 class 文件很大一部分数据，里面存放着各式各样的常量信息，包括数字和字符串常量、类和接口名、字段和方法名等。本节将详细介绍常量池和各种常量。  常量池在 class 文件中格式123456ClassFile &amp;#123;  ...  u2 constant_pool_count;	//常量池大小  cp_info constant_pool[constant_pool_coun">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://oi8e3sh89.bkt.clouddn.com/image/jvm/%E5%B8%B8%E9%87%8F%E6%B1%A0%E4%B8%AD%E5%B8%B8%E9%87%8F%E9%A1%B9%E7%BB%93%E6%9E%84%E8%A1%A8.png">
<meta property="og:updated_time" content="2019-09-01T11:13:24.305Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(5)-分析class文件-常量池">
<meta name="twitter:description" content="常量池占据了 class 文件很大一部分数据，里面存放着各式各样的常量信息，包括数字和字符串常量、类和接口名、字段和方法名等。本节将详细介绍常量池和各种常量。  常量池在 class 文件中格式123456ClassFile &amp;#123;  ...  u2 constant_pool_count;	//常量池大小  cp_info constant_pool[constant_pool_coun">
<meta name="twitter:image" content="http://oi8e3sh89.bkt.clouddn.com/image/jvm/%E5%B8%B8%E9%87%8F%E6%B1%A0%E4%B8%AD%E5%B8%B8%E9%87%8F%E9%A1%B9%E7%BB%93%E6%9E%84%E8%A1%A8.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/05/09/手写JVM系列-5-分析class文件-常量池/">





  <title>手写JVM系列(5)-分析class文件-常量池 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/09/手写JVM系列-5-分析class文件-常量池/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(5)-分析class文件-常量池</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-09T10:30:01+08:00">
                2017-05-09
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,536
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <blockquote>
<p>常量池占据了 class 文件很大一部分数据，里面存放着各式各样的常量信息，包括数字和字符串常量、类和接口名、字段和方法名等。本节将详细介绍常量池和各种常量。</p>
</blockquote>
<h1 id="常量池在-class-文件中格式"><a href="#常量池在-class-文件中格式" class="headerlink" title="常量池在 class 文件中格式"></a>常量池在 class 文件中格式</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ClassFile &#123;</span><br><span class="line">  ...</span><br><span class="line">  u2 constant_pool_count;	<span class="comment">//常量池大小</span></span><br><span class="line">  cp_info constant_pool[constant_pool_count-<span class="number">1</span>]; <span class="comment">//常量池</span></span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先读出常量池的大小，这是一个 u2 类型的数据，因此，这也表明了常量池最大为 2^16-1，如果你不是故意为难虚拟机，将工程中所有的代码都写到一个 class 文件中，相信这已经足够用了。</p>
<p>接下来根据这个大小,生成常量信息数组，注意：</p>
<ol>
<li>表头给出的常量池大小比实际大 1,所以这样的话,虽然可能生成了这么大的,但是 0 不使用,直接从 1 开始;</li>
<li>有效的常量池索引是 1~n–1。0 是无效索引，表示不指向任何常量</li>
<li>CONSTANT_Long_info 和 CONSTANT_Double_info 各占两个位置。也就是说，如果常量池中存在这两种常量，实际的常量数量比 n–1 还要少，这也导致了 1~n–1 的某些数也会变成无效索引。</li>
</ol>
<h1 id="常量池分类"><a href="#常量池分类" class="headerlink" title="常量池分类"></a>常量池分类</h1><p>常量池中的常量分为两类：字面量 和 符号引用</p>
<ul>
<li><p>字面量:文本字符串,声明为 final 的常量值等</p>
<ul>
<li><p>数字常量</p>
</li>
<li><p>字符串常量</p>
<p>​</p>
</li>
</ul>
</li>
<li><p>符号引用:Javac 在编译的时候,没有像 c 语言那样的”连接”这一步,而是在加载 class 文件的时候动态加载,拿到该符号引用指向的字符串,再使用反射,加载相应的类.</p>
<ul>
<li>类</li>
<li>接口</li>
<li>字段</li>
<li>方法</li>
</ul>
</li>
</ul>
<p>字面量是可以直接获取到其值的,而符号引用是通过索引直接或者间接指向 CONSTANT_Utf8_info 常量,然后拿到其字面量的;</p>
<h1 id="常量池具体类型"><a href="#常量池具体类型" class="headerlink" title="常量池具体类型"></a>常量池具体类型</h1><p>常量池具体可以分为以下 14 中类型，其基本结构都是由一个 u1 的 tag，后面跟一个具体类型的数据组成。</p>
<p><img src="http://oi8e3sh89.bkt.clouddn.com/image/jvm/%E5%B8%B8%E9%87%8F%E6%B1%A0%E4%B8%AD%E5%B8%B8%E9%87%8F%E9%A1%B9%E7%BB%93%E6%9E%84%E8%A1%A8.png" alt="常量池中的 14 种常量项的结构总表"></p>
<p>按照常量池的分类一节，将这 14 中分为两类</p>
<ul>
<li>字面量：<ul>
<li>CONSTANT_Integer</li>
<li>CONSTANT_Float</li>
<li>CONSTANT_Long</li>
<li>CONSTANT_Double</li>
<li>CONSTANT_Utf8</li>
</ul>
</li>
<li>符号引用：剩余的 10 种。</li>
</ul>
<p>下面分别从字面量大类和符号引用大类中各选两个有代表性的常量进行讲解。</p>
<h2 id="CONSTANT-Integer"><a href="#CONSTANT-Integer" class="headerlink" title="CONSTANT_Integer"></a>CONSTANT_Integer</h2><p>CONSTANT_Integer_info 使用 4 字节存储整数常量，其结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_Integer_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u4 bytes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因此我们在读到 tag 为 CONSTANT_Integer 时，接下来需要读取 4 字节的数据，从而拼接成这一个整数。</p>
<p>float，long，double 和 int 是类似的，读到对应的 tag，分别去读 4,8,8 字节的数据拼接起来，就是实际的数值。</p>
<h2 id="CONSTANT-Utf8"><a href="#CONSTANT-Utf8" class="headerlink" title="CONSTANT_Utf8"></a>CONSTANT_Utf8</h2><p>CONSTANT_Utf8 类型代表的是常量池中真正的字符串，其结构定义如下，读取到对应的 tag 后，后面是一个 u2 的数据，表明字符串的长度 len，接下来是长度为 len 的字节，代表真正的字符串。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_Utf8_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u2 length;</span><br><span class="line">  u1 bytes[length];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是这里要注意的是，字符串在 class 文件中是以 MUTF-8（Modified UTF-8）方式编码的。MUTF-8 编码方式和 UTF-8 大致相同，但并不兼容。<br>差别有两点：一是 null 字符（代码点 U+0000）会被编码成 2 字节：0xC0、0x80；二是补充字符（Supplementary Characters，代码点大于U+FFFF 的 Unicode 字符）是按 UTF-16 拆分为代理对（Surrogate Pair）分别编码的。具体转换方法请看<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/classfile/ConstantUtf8Info.java" target="_blank" rel="noopener">源码</a>，这里的转换方法是直接根据 java.io.DataInputStream.readUTF（）方法改写的。将读到的 byte 数组经过转码之后得到其代表的具体字符串。</p>
<p>常量类型中有一个 ConstantStringInfo，这个常量的名字迷惑性比较强，但是它里面并没有保存真正的字符串，而是保存了一个指向常量池中的索引，这个索引对应的常量类型一定是 CONSTANT_Utf8，这个常量中的字符串才是 ConstantStringInfo 中想表达的字符串。</p>
<h2 id="CONSTANT-Class"><a href="#CONSTANT-Class" class="headerlink" title="CONSTANT_Class"></a>CONSTANT_Class</h2><p>CONSTANT_Class_info 常量表示类或者接口的符号引用，指向是接口或者类名。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_Class_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u2 name_index;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其 name_index 是常量池索引，指向 <code>CONSTANT_Utf8_info</code> 常量。所以如果想真正的拿到当前 class 的全限定名，需要通过 name_index 先得到常量池中的 <code>CONSTANT_Utf8_info</code>，然后在获取其中的值。</p>
<h2 id="CONSTANT-NameAndType"><a href="#CONSTANT-NameAndType" class="headerlink" title="CONSTANT_NameAndType"></a>CONSTANT_NameAndType</h2><p>CONSTANT_NameAndType_info 给出字段或方法的名称和描述符。CONSTANT_Class_info 和 CONSTANT_NameAndType_info 加在一起可以唯一确定一个字段或者方法。其结构如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_NameAndType_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u2 name_index;</span><br><span class="line">  u2 descriptor_index;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>字段或方法名由 name_index 给出，字段或方法的描述符由 descriptor_index 给出。name_index 和 descriptor_index 都是常量池索引，指向 CONSTANT_Utf8_info 常量。字段和方法名就是代码中出现的（或者编译器生成的）字段或方法的名字。</p>
<p>Java 虚拟机规范定义了一种简单的语法来描述字段和方法，可以根据下面的规则生成描述符。</p>
<ol>
<li><p>类型描述符。</p>
<ul>
<li>基本类型 byte、short、char、int、long、float 和 double 的描述符是单个字母，分别对应 B、S、C、I、J、F 和 D。注意，long 的描述符是 J 而不是 L。</li>
<li>引用类型的描述符是“L＋类的完全限定名＋分号”</li>
<li>数组类型的描述符是“[＋数组元素类型描述符”</li>
</ul>
</li>
<li><p>字段描述符就是字段的类型描述符。</p>
</li>
<li><p>方法描述符格式是：“（按参数顺序的参数类型描述符）+返回值类型描述符”，其中 void 返回值由单个字母 V 表示。</p>
</li>
</ol>
<h1 id="常量池类型总结"><a href="#常量池类型总结" class="headerlink" title="常量池类型总结"></a>常量池类型总结</h1><p>可以把常量池中的常量分为两类：字面量（literal）和符号引用（symbolic reference）。字面量包括数字常量和字符串常量，符号引用包括类和接口名、字段和方法信息等。除了字面量，其他常量都是通过索引指向 CONSTANT_Utf8_info 常量来获取其对应的字符串。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/05/09/手写JVM系列-5-分析class文件-常量池/" title="手写JVM系列(5)-分析class文件-常量池">https://zachaxy.github.io/2017/05/09/手写JVM系列-5-分析class文件-常量池/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/09/手写JVM系列-4-分析class文件/" rel="next" title="手写JVM系列(4)-分析class文件">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(4)-分析class文件
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/05/09/手写JVM系列-6-分析class文件-属性表/" rel="prev" title="手写JVM系列(6)-分析class文件-属性表">
                手写JVM系列(6)-分析class文件-属性表 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#常量池在-class-文件中格式"><span class="nav-number">1.</span> <span class="nav-text">常量池在 class 文件中格式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常量池分类"><span class="nav-number">2.</span> <span class="nav-text">常量池分类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常量池具体类型"><span class="nav-number">3.</span> <span class="nav-text">常量池具体类型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#CONSTANT-Integer"><span class="nav-number">3.1.</span> <span class="nav-text">CONSTANT_Integer</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CONSTANT-Utf8"><span class="nav-number">3.2.</span> <span class="nav-text">CONSTANT_Utf8</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CONSTANT-Class"><span class="nav-number">3.3.</span> <span class="nav-text">CONSTANT_Class</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CONSTANT-NameAndType"><span class="nav-number">3.4.</span> <span class="nav-text">CONSTANT_NameAndType</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常量池类型总结"><span class="nav-number">4.</span> <span class="nav-text">常量池类型总结</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
